let express = require('express');
let router = express.Router();


let user = require('../models/user');

function jsonData(code, d, msg) {
	return ({error_code: code, data: d, msg: msg});
}
let parsePostBody = (req, done) => {
	let arr = [];
	let chunks;
	req.on('data', buff => {
		arr.push(buff);
	});
	req.on('end', () => {
		chunks = Buffer.concat(arr);
		done(chunks);
	});
};


router.post('/login', function (req, res, next) {
	res.header("Access-Control-Allow-Credentials","true");
	res.header("Access-Control-Allow-Origin", req.headers.origin);
	res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
	res.header("Access-Control-Allow-Headers", "X-Requested-With");
	res.header('Access-Control-Allow-Headers', 'Content-Type');
	let submit = function (data) {
		user.login(data, function (d) {
			if (data.u_name == d[0].u_name && data.u_pwd == d[0].u_pwd) {
				req.session.regenerate(function(err) {
					req.session.loginUser = {
						id:d[0].id,
						nickname:d[0].nickname,
						u_name:d[0].u_name,
						headicon:d[0].headicon,
					};
					res.json(jsonData(0, d[0],'登录成功'));
				});
			} else {
				res.json(jsonData(-2, null,'登录失败'));
			}
		});
	};
	if( req.body){
		let json = req.body;
		if (!json.u_name) { res.json(jsonData(-1, {})); }
		let data = { u_name: json.u_name, u_pwd: json.u_pwd };
		submit(data);
	}else{
		parsePostBody(req, (chunks) => {
			let json = JSON.parse(chunks.toString());    // 关键代码
			if (!json.u_name) { res.json(jsonData(-1, {})); }
			let data = { u_name: json.u_name, u_pwd: json.p_pwd};
			submit(data);
		});
	}
});




// 退出登录
router.all('/logout', function(req, res, next){
	res.header("Access-Control-Allow-Credentials","true");
	res.header("Access-Control-Allow-Origin", req.headers.origin);
	res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
	res.header("Access-Control-Allow-Headers", "X-Requested-With");
	res.header('Access-Control-Allow-Headers', 'Content-Type');
	// 备注：这里用的 session-file-store 在destroy 方法里，并没有销毁cookie
	// 所以客户端的 cookie 还是存在，导致的问题 --> 退出登陆后，服务端检测到cookie
	// 然后去查找对应的 session 文件，报错
	// session-file-store 本身的bug

	req.session.destroy(function(err) {
		if(err){
			res.json({ret_code: 2, ret_msg: '退出登录失败'});
			return;
		}
		let identityKey = 'skey';
		res.clearCookie(identityKey);
		res.json(jsonData(0, null,'退出登录成功' ));
	});
});

router.all("/islogin", function (req, res, next) {
	// 服务器端 Access-Control-Allow-Credentials = true时，参数Access-Control-Allow-Origin 的值不能为 '*'
	res.header("Access-Control-Allow-Credentials","true");
	res.header("Access-Control-Allow-Origin", req.headers.origin);
	res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
	res.header("Access-Control-Allow-Headers", "X-Requested-With");
	res.header('Access-Control-Allow-Headers', 'Content-Type');
	let sess = req.session;
	/*TODO 为什么直接打开接口访问是可以的，用js掉就不行了呢？*/
	let loginUser = sess.loginUser;
	let loginCode = loginUser?0:-1;
	res.json(jsonData(loginCode, loginUser ));
});

module.exports = router;
